package cn.caskm.souvenirshopsystem.interceptors;

import cn.caskm.souvenirshopsystem.config.JwtProperties;
import cn.caskm.souvenirshopsystem.constants.BizConstants;
import cn.caskm.souvenirshopsystem.exceptions.UnLoginException;
import cn.caskm.souvenirshopsystem.utils.JwtUtil;
import cn.caskm.souvenirshopsystem.utils.UserContext;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        String token = request.getHeader(BizConstants.TOKEN);
        if (StrUtil.isBlank(token)) {
            // token不存在，拦截
            throw new UnLoginException();
        }

        // 2.校验token
        Claims claims = JwtUtil.parseToken(token, jwtProperties.getPublicKey());
        if (claims == null) {
            throw new UnLoginException();
        }

        // 3、从token拿到用户id
        Long userId = claims.get(BizConstants.USER_INFO, Long.class);

        // 4.保存用户信息到ThreadLocal
        UserContext.setUser(userId);

        // 5.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户信息
        UserContext.removeUser();
    }
}
